<?php 
namespace Home\Controller ;
use User\Api\UserApi;

class ApiController extends HomeController {
	function _initialize(){
		parent::_initialize();
	}




	function getLocation(){
		 $url = "http://api.map.baidu.com/geocoder?location=%s,%s&output=json&key=28bcdd84fae25699606ffad27f8da77b";

		 	$url = sprintf($url,I('get.lat'),I("get.lon"));

			$res = file_get_contents($url);
			$res = json_decode($res);
			
			$return = AJAX();
			if($res->status == "OK")
			{
				
				$citys = json_decode(file_get_contents("./citycode.json"),true);
				$citys['topCitys'] = array(
					"id" => $res->result->cityCode,
					"city" => $res->result->addressComponent->city,
					);
				//生成一个标志
				$flag = time();
				S($flag,json_encode($citys));
				$temp = array(
					"time" => $flag,
					"city" => $res->result->addressComponent->city,
					"id"   =>  $res->result->cityCode,
					);
				$return["data"] = $temp;
				$this->ajaxReturn($return);
			}
	}

	function getJson(){
		$flag = I('get.time');
		$json = S($flag);
		echo $json;
	}


	function test(){
		$s = file_get_contents("./citycode.txt");
		$arr = explode("\n",$s);
		$json = array();
	
		foreach($arr as $k=>$v){
			$temp = explode(" ", $v);
			$json[$k] = array();
			$json[$k]["id"] = $temp[0];
			$json[$k]['city'] = $temp[1];
		}

		$arr = array();
		$arr['citys'] = $json;
		file_put_contents("./citycode.json", json_encode($arr));
	}

	/**小雨的客户端
	 * 接受lat long 插入数据库
	 * @return [type] [description]
	 */
	function post(){
		$lon = I('get.lon');
		$lat = I('get.lat');

		$data = array(
			'lon' => $lon,
			'lat' => $lat,
			'time' => time(),
			);
		M('Xy')->add($data);
	}

	/**
	 * 首页Movies数据API 
	 */
	function moviesIndexApi($p = 1){
		$ajax = AJAX();
		$res = M('Movies')->limit(($p - 1) * 10 , 10 )->select(); 
		$ajax['data'] = $res ; 
		ajaxReturn($ajax);
	}


	//发送短信接口
	function sendsms(){
		if(IS_POST)
		{
			$mobile = I('post.mobile');

			//检查用户名是否存在 
			$code = get_rand();
			$content = '验证码' .$code ;  
			semd_msg($mobile,$content);
			$return = AJAX();
			$return['data'] = $content;
			ajax_log($return);
			/*******写入短信日志***/
			$sms = array(
				'code' => $code , 
				'mobile' => $mobile , 
				'time' => (time() + 30 * 6) ,
				'use' => 0 ,
				);
			M('Sms')->where('mobile='.$mobile)->save(array('use'=>1));
			M('Sms')->add($sms);
			ajaxReturn($return);
		}
	}

	/**
	 * 注册接口
	 */
	function register(){
		if(IS_POST){
			$return = AJAX();
			$mobile = I('post.username') ; 
			$code = I('post.smscode') ; 
			//验证短信验证码
			if(!check_sms($mobile , $code ))
			{

				$return['status'] = 0 ;
				$return['info'] = '短信验证码错误' ;
				ajaxReturn($return);
			}
			
			$mobile = I('post.username') ; 
			$password = I('post.password') ; 
			$repassword = I('post.repassword') ; 

			if($password != $repassword) 
			{

				$return['status'] = 0 ; 
				$return['info'] = '两次密码不一致' ; 
				ajaxReturn($return);
			}
			if(!preg_match('/^1[3|5|7|8]\d{9}$/',$mobile) || !preg_match('/\w{6,16}/',$password))
			{

				$return['status'] = 0 ; 
				$return['info'] = '账号或密码格式有误' ; 
				ajaxReturn($return);
			}
			/* 调用注册接口注册用户 */
            $User = new UserApi;
			$uid = $User->register($mobile, $password, $mobile . '@qq.com');
			if(0 < $uid){ //注册成功
				//TODO: 发送验证邮件
				ajaxReturn($return);
			} else { //注册失败，显示错误信息
				
			}
		}
	}

	/**
	 * 登陆接口 
	 */
	function login(){
		if(IS_POST)
		{
			$return = AJAX();
			$user = new UserApi ; 
			$username = I('post.username') ; 
			$password = I('post.password') ;
			$uid = $user->login($username , $password );

			if(0 < $uid  )
			{
				$Member = D('Member') ; 
				if($Member->login($uid))
				{
					$return['data']['username'] = $username ; 
					$return['data']['password'] = $password ;  
					$return['data']['uid'] = $uid ; 
				} else {

					$return['status'] = 0 ; 
					$return['info'] = '登录失败' ; 
				}
			} else {
				$return['status'] = 0 ; 
				switch ($uid) {
					case -1 : $error = '用户名不存在或被禁用!' ; break ; 
					case -2 : $error = '密码错误!' ; break ; 
					default : $error = '未知错误!' ; break ; 
				}
				$return['info'] = $error ; 
			}
			if(isset($_SESSION['from']))
			{
				$return['url'] ='http://'.$_SERVER['SERVER_NAME'] . '/' .$_SESSION['from'];
			}
			$return['info'] = "登录成功";
			ajaxReturn($return);
		}
	}


	//个人中心代码 
	function ucenter(){
		if(IS_POST)
		{	
			$user_id = I('post.uid');
			$res = M('UcenterMember')->where(array("id"=>$user_id))->find();
			
			$return = AJAX() ; 
			$return['data'] = $tpl ; 
			$return['info'] = '登陆成功' ;
			ajaxReturn($return);
		}
	}
	/**
	 * 获取详情
	 * 第二天的详情
	 */
	function getDetail(){
		$movies_info = $_SESSION['movies_info'];

		$mid = $movies_info['movie']['id'];
		$cid = $movies_info['cinema']['id'];
		 //电影院场次信息
        $map = array('mid'=>$mid,'cid'=>$cid);
        $map['start_time'][0] = array('gt',strtotime(date('Y-m-d')) + 24 * 3600);
        $map['start_time'][1] = array('lt',(strtotime(date('Y-m-d')) + 24 * 3600 + 24 * 3600));

        $field = "r.name,r.id AS rid ,m.*";
        $manage = M('Manage')->alias('m')->field($field)
                        ->join("LEFT JOIN api_cinema_rooms AS r ON r.id = m.rid")
                        ->where($map)->select();
        $this->assign('manage',$manage);
        $this->display();


	}
	/**
	 * 通过rid获取当前房间的位置信息
	 * @return [type] [description]
	 */
	function getSeat($manageid = null){

		if(!$manageid)
		{
			exit();
		}
		/**
		 * 思想
		 * 根据此房间 ， 此时间段 ， 去查询订单 ， 选择一个count 并且 获取
		 * 横与列的坐标 。
		 * 都是已选的 ， 剩下的即是未选择的 。 
		 * 先不考虑那些问题。画出大概模型。
		 */
		$info = M('Manage')->where('id='.$manageid)->find();

		$seat = M('CinemaRooms')->where('id='.$info['rid'])->find();
		$return = AJAX();
        //已经售出的作为列表 
        $map = array();
        /**
         * 思路
         * 首先不做延迟思想考虑
         * 只要是 order_movies start_time = 此电影 ，并且 room_id = 此rid 的 ， 就是同一场电影和房间。
         * 全局都不做延迟思想考虑
         * 抢票去吧
         * order_status = 1 
         * pay_status = 2 
         * pay_time > 0 
         * confirm > 0 
         */
        $map['o.order_status'] = 1;
        $map['o.pay_status'] = 2 ;
        $map['o.pay_time'] = array('gt',0);
        $map['o.confirm_time'] = array('gt',0);
        $map['om.start_time'] = $info['start_time'];
        $map['om.room_id'] = $info['rid'];
        $field = "om.row,om.col";
        $hasSell = M('OrderMovies')->alias("om")->field($field)
                                   ->join("LEFT JOIN api_orders AS o ON o.order_sn = om.order_sn")
                                   ->where($map)
                                   ->select();
        
		$return['data'] = $seat ; 
		$return['hasSell'] = $hasSell;

		ajaxReturn($return);

	}


	/**
	 * 支付页面
	 */
	function checkout(){
		if(IS_POST)
		{	

			$return = AJAX();
			if(!isset($_SESSION['movies_info']))
			{
				exit();
			}
			$cinema = $_SESSION['movies_info']['cinema'] ;
			$movie = $_SESSION['movies_info']['movie'] ; 

			$seat = I('post.seat');
			
			$manageid = I('post.manageid') ; 
			/************判断用户是否登陆***********************/
			if(!is_login())
			{
				$return['status'] = 2 ; //未登录的状态 .
				$_SESSION['from'] = url('index/selectsit',array('manageid'=>$manageid));
				ajaxReturn($return);
			} 
			/************* 判断是否被买了 。	************/
			$map = array();
			$map['o.order_status'] = 1;
       		$map['o.pay_status'] = 2 ;
       		$map['o.pay_time'] = array('gt',0);
       		$map['o.confirm_time'] = array('gt',0);
       		$map['om.start_time'] = $info['start_time'];
       		$map['om.room_id'] = $info['rid'];
       		$field = "om.row,om.col";
       		$hasSell = M('OrderMovies')->alias("om")->field($field)
       		                           ->join("LEFT JOIN api_orders AS o ON o.order_sn = om.order_sn")
                                	   ->where($map)
                                	   ->select();
            foreach($seat as $k => $v)
            {
            	if(in_array($v , $hasSell))
            	{
            		$return['status'] = 0;
            		$return['info'] = "此座位已经售出";
            		ajaxReturn($return);
            	}
            }
            
			//生成订单 。
			$order_sn = get_order_sn();

			while((M('Orders')->where('order_sn='.$order_sn)->count()) > 0 )
			{
				$order_sn = get_order_sn();
			}
			//影院信息 
			$manage = M('Manage')->where('id='.$manageid)->find();
			$user = session('user_auth') ;
			$time = time() ;
			//订单主表
			$order = array(
				"order_sn" =>  $order_sn, 
				"order_status" => 0 ,
				"pay_status" => 0 ,
				"add_time" => $time ,
				"pay_time" => '',
				"confirm_time" => "",
				"user_id" => $user['uid'],
				"mobile" => $user['username'],
				"price" => ($manage['price'] * count($seat)),
				);
			$oid = M('Orders')->add($order);
			//订单从表 
			$order_extend = array();

			foreach($seat as $k=>$v)
			{
				$order_extend[$k]['movie_id'] = $movie['id'];
				$order_extend[$k]['cinema_id'] = $cinema['id'];
				$order_extend[$k]['start_time'] = $manage['start_time'] ;
				$order_extend[$k]['end_time'] = $manage['end_time']; 
				$order_extend[$k]['row'] = $v['row'];
				$order_extend[$k]['col'] = $v['col'];
				$order_extend[$k]['room_id'] = $manage['rid'];
				$order_extend[$k]['order_sn'] = $order_sn ;
			}

			
			M('OrderMovies')->addAll($order_extend);

			//操作成功。ajax返回，跳转到支付页面 。
			$return['url'] = url('index/pay',array('orderNo'=>$order_sn));
			ajaxReturn($return);
		}
	}

	/**
	 * 订单列表获取座位号接口
	 */
	function getOrderedSeat($orderno = null){
		$return = AJAX();
		if(!$orderno)
		{
			$return['info'] = "无效的订单号";
			$return['status'] = 0;
			ajaxReturn($return);
		}
		$map = array();
		$map['om.order_sn'] = $orderno ; 
		$field = "om.start_time , om.end_time,om.row,om.col,".
				 "cm.name AS rname,".
				 "c.title AS cname,".
				 "m.title AS mname";
		$data = M('OrderMovies')->alias("om")->field($field)
								->join("LEFT JOIN api_movies AS m ON m.id = om.movie_id")
								->join("LEFT JOIN api_cinema AS c ON c.id = om.cinema_id")
								->join("LEFT JOIN api_cinema_rooms AS cm ON cm.id = om.room_id")
							->where($map)->select();
		$return['data'] = $data ; 
		ajaxReturn($return);
	}
	/**
	 * 修改密码
	 */
	function changePassword(){
		
		if(!is_login())
		{
			$this->error('请登录');
		}


		if ( IS_POST ) {
            //获取参数
            $return  = AJAX();
            $uid        =   is_login();
            $password   =   I('post.old');
            $repassword = I('post.repassword');
            $data['password'] = I('post.password');
            if(empty($password)) {$return['info'] = '请输入原密码';$return['status'] = 0;ajaxReturn($return); }
            if(empty($repassword)) {$return['info'] = '请输入确认密码';$return['status'] = 0;ajaxReturn($return); }
            if(empty($data['password'])) {$return['info'] = '请输入密码';$return['status'] = 0;ajaxReturn($return); }
            $p = "/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,22}$/";
            
            if($repassword != $data['password'])
            {
            	$return['status'] = 0;
            	$return['info'] = '两次密码输入不一致';
            	ajaxReturn($return);
            }

            if(!preg_match($p, $repassword))
            {
            	$return['status'] = 0;
            	$return['info'] = '密码格式不正确';
            	ajaxReturn($return);
            }

            $Api = new UserApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if($res['status']){
               $return['info'] = '修改成功<br>请重新登陆';
               session_destroy();
               $return['url'] = url('index/login');

            }else{
            	$return['status'] = 0;
            	$return['info'] = $res['info'];
            }
            ajaxReturn($return);
        }

	}

	/**
	 * 退出登录
	 */
	function logout(){

		if(is_login())
		{
			D('Member')->logout();
			session_destroy();
			$return['url'] = url('index/index');
			exit(json_encode($return));
		}
		$this->error('傻逼!!!!!!');
	}

}


 ?>